package com.sihai.ehr.web.action.salary;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.SalaryCustomDetail;
import com.sihai.ehr.model.biz.SalaryStructure;
import com.sihai.ehr.model.biz.SalaryStructureDetail;
import com.sihai.ehr.model.sys.ExaminePeriodEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.SalaryFrameworkEnum;
import com.sihai.ehr.model.sys.SalaryStructureEnum;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.SalaryStructService;
import com.sihai.ehr.web.action.EHRAction;

/**
 * 薪资结构控制器
 * 
 * @author henry
 * 
 */
@Results({ @Result(name = "main", location = "salary_main.jsp"),
		@Result(name = "struct_manage", location = "struct_manage.jsp"),
		@Result(name = "list", location = "struct_manage_list.jsp") })
public class SalaryStructAction extends EHRAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2106672426606254873L;

	private Log log = LogFactory.getLog(SalaryStructAction.class);

	@BeanInject
	private OrganizationService organizationService;
	@BeanInject
	private SalaryStructService salaryStructService;

	private List<Organization> organizations;

	private SalaryStructure structure;
	private LimitedList<SalaryStructure> structures;
	private Long structId;
	private String ids;

    private LimitedList<Object[]> structureList;
 // 补贴项目数
 	private int subsidyItemLength = 0;
 	// 扣款项目数
 	private int detainItemLength = 0;
 	
	@Action("/salary/struct_main")
	@Override
	public String execute() throws Exception {
		listTitle = "薪资架构管理";
		listAction = "/salary/struct_list.xhtml";
		organizations = organizationService
				.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = false;
		return "main";
	}

	@Action("/salary/struct_list")
	public String list() {
		listAction = "/salary/struct_list.xhtml";
		structures = salaryStructService.find(organizationId, createLimit(),
				createSorter());
		paging(structures);
		setPageUrl("salary/struct_list.xhtml");
		return "list";
	}

	
	@Action("/salary/struct_manage")
	public String dispatchInsurance() throws Exception {
		if (structId == null || structId < 0) { // 添加
			structure = new SalaryStructure();
			structure.setOrganization(organizationService.get(organizationId));
		} else { // 修改
			structure = salaryStructService.get(structId);
			if (structure.getDetails() != null && structure.getDetails().size() > 0) {
				for (Iterator iterator = structure.getDetails().iterator(); iterator.hasNext();) {
					SalaryStructureDetail type = (SalaryStructureDetail) iterator.next();
					if (type.getStructType() == SalaryStructureEnum.subsidy) {
						subsidyItemLength++;
					} else {
						detainItemLength++;
					}

				}
			}
		}
		return "struct_manage";
	}
	
	/**
	 * 保存薪资框架
	 * @return
	 * @throws Exception
	 */
	@Action("/salary/post_structure")
	public String postStructure() throws Exception{
		if (structure == null) {
			if (log.isErrorEnabled()) {
				log.error("提交数据为空");
				return ERROR;
			}
		}

		if (structure.getId() == null) {
			// 添加
		} else {
			// 修改
			/**
			 * 删除方案项目细节
			 */
			salaryStructService.deleteStructureDetails(structure.getId());
		}
		Set<SalaryStructureDetail> details = new HashSet<SalaryStructureDetail>();
		// subsidy
		String[] schemeTitle_subsidy = getParameterValues("schemeTitle_subsidy");
		String[] linkedDataType_subsidy = getParameterValues("linkedDataType_subsidy");
		String[] linkedDataId_subsidy = getParameterValues("linkedDataId_subsidy");
		String[] linkedDataTitle_subsidy = getParameterValues("linkedDataTitle_subsidy");
		String[] unitCost_subsidy = getParameterValues("unitCost_subsidy");
		String[] fixedCost_subsidy = getParameterValues("fixedCost_subsidy");
		String[] periodType_subsidy = getParameterValues("periodType_subsidy");
		String[] periodComputeMode_subsidy = getParameterValues("periodComputeMode_subsidy");
		
		// detain
		String[] schemeTitle_detain = getParameterValues("schemeTitle_detain");
		String[] linkedDataType_detain = getParameterValues("linkedDataType_detain");
		String[] linkedDataId_detain = getParameterValues("linkedDataId_detain");
		String[] linkedDataTitle_detain = getParameterValues("linkedDataTitle_detain");
		String[] unitCost_detain = getParameterValues("unitCost_detain");
		String[] fixedCost_detain = getParameterValues("fixedCost_detain");
		String[] periodType_detain = getParameterValues("periodType_detain");
		String[] periodComputeMode_detain = getParameterValues("periodComputeMode_detain");
		
		if (schemeTitle_subsidy != null && schemeTitle_subsidy.length > 0) {
			for (int i = 0; i < schemeTitle_subsidy.length; i++) {
				SalaryStructureDetail detail = new SalaryStructureDetail();
				detail.setSchemeTitle(schemeTitle_subsidy[i]);
				detail.setLinkedDataType(SalaryFrameworkEnum.valueOf(linkedDataType_subsidy[i]));
				detail.setLinkedDataId(Long.parseLong(linkedDataId_subsidy[i]));
				detail.setLinkedDataTitle(linkedDataTitle_subsidy[i]);
				detail.setUnitCost(unitCost_subsidy[i] == null || unitCost_subsidy[i].trim().isEmpty() ? 0F : Float.parseFloat(unitCost_subsidy[i]));
				detail.setFixedCost(fixedCost_subsidy[i] == null || fixedCost_subsidy[i].trim().isEmpty() ? 0F : Float.parseFloat(fixedCost_subsidy[i]));
				detail.setPeriodType(ExaminePeriodEnum.valueOf(periodType_subsidy[i]));
				detail.setPeriodComputeMode(Integer.parseInt(periodComputeMode_subsidy[i]));
				detail.setStructType(SalaryStructureEnum.subsidy);
				structure.addDetailItem(detail);
			}
		}

		if (schemeTitle_detain != null && schemeTitle_detain.length > 0) {
			for (int i = 0; i < schemeTitle_detain.length; i++) {
				SalaryStructureDetail detail = new SalaryStructureDetail();
				detail.setSchemeTitle(schemeTitle_detain[i]);
				detail.setLinkedDataType(SalaryFrameworkEnum.valueOf(linkedDataType_detain[i]));
				detail.setLinkedDataId(Long.parseLong(linkedDataId_detain[i]));
				detail.setLinkedDataTitle(linkedDataTitle_detain[i]);
				detail.setUnitCost(unitCost_detain[i] == null || unitCost_detain[i].trim().isEmpty() ? 0F : Float.parseFloat(unitCost_detain[i]));
				detail.setFixedCost(fixedCost_detain[i] == null || fixedCost_detain[i].trim().isEmpty() ? 0F : Float.parseFloat(fixedCost_detain[i]));
				detail.setPeriodType(ExaminePeriodEnum.valueOf(periodType_detain[i]));
				detail.setPeriodComputeMode(Integer.parseInt(periodComputeMode_detain[i]));
				detail.setStructType(SalaryStructureEnum.detain);
				structure.addDetailItem(detail);
			}
		}
		// 保存数据
		try {
			salaryStructService.save(structure);
		} catch (Exception e) {
			log.equals(e.getMessage());
			return ERROR;
		}
		return "main";
	}


    //设置代理人
    @Action(value = "/ajax/salary-structe-find", results = {@Result(name = "success", type = "json", params = {"root", "structureList"})
    })
    public String findForGrade() {
        if(organizationId == null){
            organizations = organizationService.findChildren(null, true, null, null);
            if (organizations != null && organizations.size() > 0) {
            	if(getCurrentUserId() > 0){
                	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
                	Iterator<Organization> it = organizations.iterator();
                	while(it.hasNext()){
                		Organization o = it.next();
                		if(o.getId() != topOrgId){
                			it.remove();
                		}
                	}
                }
                organizationId = organizations.get(0).getId();
            }
        }

        try {
            structureList = salaryStructService.findForGrade(organizationId, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }
    
    /**
	 * 删除自定义方案
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/salary/struct_delete", results = { @Result(name = "success", type = "plainText") })
	public String deleteStruct() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			try {
				salaryStructService.deleteStructures(ids);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error(e.getMessage());
				}
				return ERROR;
			}

		}

		return SUCCESS;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public SalaryStructure getStructure() {
		return structure;
	}

	public void setStructure(SalaryStructure structure) {
		this.structure = structure;
	}

	public LimitedList<SalaryStructure> getStructures() {
		return structures;
	}

	public void setStructures(LimitedList<SalaryStructure> structures) {
		this.structures = structures;
	}

	public Long getStructId() {
		return structId;
	}

	public void setStructId(Long structId) {
		this.structId = structId;
	}
	
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

    public LimitedList<Object[]> getStructureList() {
        return structureList;
    }
    
	public int getSubsidyItemLength() {
		return subsidyItemLength;
	}

	public void setSubsidyItemLength(int subsidyItemLength) {
		this.subsidyItemLength = subsidyItemLength;
	}

	public int getDetainItemLength() {
		return detainItemLength;
	}

	public void setDetainItemLength(int detainItemLength) {
		this.detainItemLength = detainItemLength;
	}
}
